package core;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import core.Record.RecordType;

public class TCPRequest {
	
	private int length = 0;
	private Map<RecordType,Record> records;
	
	public TCPRequest(String mxitid,MXitCommandType cmd,List<Field> msgFields){
		
		RecordType type = RecordType.USER;
		this.records.put(type, new Record(type,mxitid));
		
		type = RecordType.CMD;
		this.records.put(type, new Record(type,String.valueOf(cmd.getId())));
		
		type = RecordType.MSG;
		this.records.put(type, new Record(type,msgFields));
	}
	
	public int getLength()
	{
		return this.length;
	}
	
	public String getUser() {
		return this.records.get(RecordType.USER).fields.get(0).getValue().toString();
	}
	
	public Record getRecord(RecordType type) {
		return this.records.get(type);	
	}
	
	public byte[] getBytes() throws UnsupportedEncodingException {
		return this.toString().getBytes("US-ASCII");
	}
	
	private void calculateByteCount() throws UnsupportedEncodingException {
		this.length = 0;
		//TODO calling getBytes each time for the length is too very inefficient, consider keeping track of length values inside Field and Record
		for(Record record:records.values()) {
			this.length+=record.getBytes().length;
		}		
	}
	
	public String toString()
	{
		//re-calculate and set length
		try {
			this.calculateByteCount();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		StringBuilder result = new StringBuilder();
		int recordIndex = 0;
		for(Record record:records.values()) {
			result.append(record.toString() + (recordIndex == records.size() ? "":Record.END));
			recordIndex++;
		}
		return result.toString();
	}
	
}
